package InputStream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 再次练习FileInputStream的基本用法
 * User: 石方旭
 * Date: 2022-10-01
 * Time: 16:54
 */
public class FileInputStreamTest2 {

    // TODO: 2022/10/1 练习FileInputStream读取数据
    /*
        FileInputStream是输入流 即 : 是将硬盘/磁盘中的数据输入到Java程序中-->需要从磁盘中读取数据
        FileOutputStream是输出流 即 : 将java程序输出到磁盘/硬盘中的-->要java程序中数据写回到磁盘
     */
    public static void FileInputSteamDemo1() throws IOException {
        try(FileInputStream fileInputStream = new FileInputStream("e://test2.txt")) {
            //使用read需要一个一个读取
            while(true){
                int readData = fileInputStream.read();
                if(readData==-1){//读取到文件末尾,不读了
                    break;
                }
                System.out.printf("%c",readData);
            }
        }
    }

    //为了提高读取的效率,我们将读取的数据放到字节数组里面
    //read(byte[])  将数据放到这个字节数组里面去 返回值是数据长度
    public static void FileInputStreamDemo2() throws IOException {
        try(FileInputStream fileInputStream = new FileInputStream("e://test2.txt")){
            byte[] bytes = new byte[4096];
            while(true){
                //读取数据放到字节数组bytes中,返回的是数据长度
                int len = fileInputStream.read(bytes);
                if(len==-1){//如果是-1就文件末尾
                    break;
                }
                for(int i =0;i<len;++i){
                    System.out.print((char)bytes[i] + " ");
                }
            }
        }
    }

    // TODO: 2022/10/1 使用Scanner来读取数据

    public static void FileInputStreamDemo3() throws IOException {
        try(FileInputStream fileInputStream = new FileInputStream("e://test2.txt")){
            try(Scanner scan = new Scanner(fileInputStream)){
                while(scan.hasNext()){
                    System.out.println(scan.next());
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //FileInputSteamDemo1();
        FileInputStreamDemo3();
    }

}
